<?php

class QuestionController extends QaController {

	/**
	 * @var string the default layout for the views.
	 * Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout = '//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters() {
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules() {
		return array(
			array('allow',
				'actions'=>array('index', 'archive', 'view'),
				'users'=>array('*'),
			),
			array('allow',
				'actions'=>array('create', 'update', 'preserve'),
				'users'=>array('@'),
			),
			array('allow',
				'actions'=>array('admin', 'delete'),
				'users'=>array('admin'),
			),
			array('deny', // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id) {
		$model = $this->loadModel($id);
		$answerModel = new Answer();

		$this->performAnswerAjaxValidation($answerModel);

		if (isset($_POST['Answer'])) {
			$answerModel->attributes = $_POST['Answer'];
			$answerModel->questionId = $id;
			if ($answerModel->save()) {
				$model->recall();
				
				$from = $answerModel->creator->email;
				$subject = Yii::app()->name . ' - Q&A: ';
				$subject .= $answerModel->question->title;
				$data = array('data'=>$answerModel);
				$view = 'qa.views.answer._mail';
				$message = $this->renderPartial($view, $data, true);
				$this->mail($from, $subject, $message);
				
				$this->redirect(array('index'));
			}
		}

		$counters = array('viewCount'=>1);
		$condition = 'id = :id';
		$params = array(':id'=>$id);
		Question::model()->updateCounters($counters, $condition, $params);

		$data = array(
			'model'=>$model,
			'answerModel'=>$answerModel,
		);
		$this->render('view', $data);
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view'
	 * page.
	 */
	public function actionCreate() {
		$model = $this->_create();

		$this->render('create', array('model'=>$model));
	}

	private function _create() {
		$model = new Question;

		$this->performAjaxValidation($model);

		if (isset($_POST['Question'])) {
			$model->attributes = $_POST['Question'];
			if ($model->save()) {
				$from = $model->creator->email;
				$subject = Yii::app()->name . ' - Q&A: ' . $model->title;
				$data = array('data'=>$model);
				$message = $this->renderPartial('_mail', $data, true);
				$this->mail($from, $subject, $message);

				$this->redirect(array('index'));
			}
		}

		return $model;
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view'
	 * page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id) {
		$model = $this->loadModel($id);

		$user = Yii::app()->user;
		if (!($user->id == 1 || $model->createdBy == $user->id)) {
			$s = 'You are not authorize to perform this action.';
			throw new CHttpException(403, $s);
		}

		$this->performAjaxValidation($model);

		if (isset($_POST['Question'])) {
			$model->attributes = $_POST['Question'];
			if ($model->save()) {
				$this->redirect(array('view', 'id'=>$model->id));
			}
		}

		$this->render('update', array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin'
	 * page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id) {
		if (Yii::app()->request->isPostRequest) {
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we
			// should not redirect the browser
			if (!isset($_GET['ajax'])) {
				$set = isset($_POST['returnUrl']);
				$this->redirect($set ? $_POST['returnUrl'] : array('admin'));
			}
		} else {
			throw new CHttpException(
				400, 'Invalid request. Please do not repeat this request again.'
			);
		}
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex() {
		$model = $this->_create();

		$config = array(
			'criteria'=>array(
				'order'=>'updatedAt DESC',
				'condition'=>"preserved = 0",
			),
		);
		$dataProvider = new CActiveDataProvider('Question', $config);
		$data = array(
			'dataProvider'=>$dataProvider,
			'model'=>$model,
		);
		$this->render('index', $data);
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin() {
		$model = new Question('search');
		$model->unsetAttributes();  // clear any default values
		if (isset($_GET['Question'])) {
			$model->attributes = $_GET['Question'];
		}

		$this->render('admin', array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id) {
		$model = Question::model()->findByPk($id);
		if ($model === null) {
			throw new CHttpException(404, 'The requested page does not exist.');
		}
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model) {
		if (isset($_POST['ajax']) && $_POST['ajax'] === 'qa-question-form') {
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

	protected function performAnswerAjaxValidation($model) {
		if (isset($_POST['ajax']) && $_POST['ajax'] === 'qa-answer-form') {
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

	public function actionPreserve($id) {
		if (Yii::app()->request->isPostRequest) {
			$this->loadModel($id)->preserve();
			if (!isset($_GET['ajax'])) {
				$set = isset($_POST['returnUrl']);
				$this->redirect($set ? $_POST['returnUrl'] : array('index'));
			}
		} else {
			throw new CHttpException(
				400, 'Invalid request. Please do not repeat this request again.'
			);
		}
	}

	/**
	 * Lists all models.
	 */
	public function actionArchive() {
		$model = new Question;

		$config = array(
			'criteria'=>array(
				'order'=>'updatedAt DESC',
				'condition'=>"preserved = 1",
			),
		);
		$dataProvider = new CActiveDataProvider('Question', $config);
		$data = array(
			'dataProvider'=>$dataProvider,
			'model'=>$model,
		);
		$this->render('archive', $data);
	}

	public function renderAnswer($data, $level) {
		if ($level) echo '<div class="answer">';
		$view = 'application.modules.qa.views.answer._view';
		$this->renderPartial($view, array('data'=>$data));
		foreach ($data->childs as $child) {
			$this->renderAnswer($child, $level + 1);
		}
		if ($level) echo '</div>';
	}

}
